 import { useState } from 'preact/hooks'
import { Card, Form, Input, Button, Select, Switch, Row, Col } from 'antd'
import { parseSchemas } from '@/utils/parser'

export default function SchemaEditor() {
  const [schemas] = useState(parseSchemas())
  const [selectedSchema, setSelectedSchema] = useState(null)
  const [form] = Form.useForm()

  return (
    <Card>
      <Row gutter={16}>
        <Col span={8}>
          <div style={{ borderRight: '1px solid #f0f0f0', paddingRight: 16 }}>
            <h3>Schemas</h3>
            <div style={{ maxHeight: '70vh', overflow: 'auto' }}>
              {Object.keys(schemas).map(name => (
                <div 
                  key={name} 
                  onClick={() => setSelectedSchema(schemas[name])}
                  style={{
                    padding: 8,
                    cursor: 'pointer',
                    background: selectedSchema?.name === name ? '#f0f5ff' : 'transparent'
                  }}
                >
                  {name}
                </div>
              ))}
            </div>
          </div>
        </Col>
        <Col span={16}>
          {selectedSchema && (
            <>
              <h3>{selectedSchema.name}</h3>
              <Form form={form} layout="vertical" initialValues={selectedSchema}>
                {Object.entries(selectedSchema.properties).map(([prop, config]) => (
                  <Form.Item
                    key={prop}
                    label={
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span>{prop}</span>
                        <span style={{ color: '#999' }}>{config.type}</span>
                      </div>
                    }
                    name={['properties', prop]}
                  >
                    <Input addonBefore={
                      <Switch 
                        checked={selectedSchema.required?.includes(prop)} 
                        onChange={checked => {
                          const required = checked 
                            ? [...(selectedSchema.required || []), prop]
                            : selectedSchema.required?.filter(r => r !== prop)
                          form.setFieldsValue({ required })
                        }}
                      />
                    } />
                  </Form.Item>
                ))}
                <Button type="primary">Save Changes</Button>
              </Form>
            </>
          )}
        </Col>
      </Row>
    </Card>
  )
}
